package com.itlong.cloud.controller.finance;

import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyArrearPeopleSelectDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyArrearPeopleSelectVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.property.IPadFaceSyncDataServiceClient;
import com.itlong.cloud.paymenthub.IPropertyArrearPeopleSelectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      欠费住户查询控制器
 * <desc/>
 *
 * @createDate 2019/05/21
 */
@RestController
@RequestMapping("/propertyValue/arrearagePeopleSelect")
@RefreshScope
public class PropertyArrearPeopleSelectController extends BaseController {

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    private IPropertyArrearPeopleSelectServiceClient iPropertyArrearPeopleSelectServiceClient;

    @Autowired
    private IPadFaceSyncDataServiceClient iPadFaceSyncDataServiceClient;

    /**
     * <desc>
     *      分页获取欠费住户信息
     * </desc>
     *
     * @param propertyArrearPeopleSelectDTO 欠费住户信息DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/05/21
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getPage")
    public Object getPage(PropertyArrearPeopleSelectDTO propertyArrearPeopleSelectDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyArrearPeopleSelectDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyArrearPeopleSelectDTO.class, request);
            if (propertyArrearPeopleSelectDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyArrearPeopleSelectDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            Page<PropertyArrearPeopleSelectVO> page = iPropertyArrearPeopleSelectServiceClient.getPage(propertyArrearPeopleSelectDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【物业-物业增值】分页获取欠费住户信息失败", e);
        }
    }

    /**
     * <desc>
     *      临时解除限制
     * </desc>
     *
     * @param propertyArrearPeopleSelectDTO 欠费住户信息DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/05/22
     */
    @ResponseBody
    @PostMapping("momentRelieve")
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.MOMENT_RELIEVE_LOG_DESC)
    public Object momentRelieve(PropertyArrearPeopleSelectDTO propertyArrearPeopleSelectDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyArrearPeopleSelectDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyArrearPeopleSelectDTO.class, request);
            if (propertyArrearPeopleSelectDTO == null || StringUtils.isBlank(propertyArrearPeopleSelectDTO.getBuildId()) || StringUtils.isBlank(propertyArrearPeopleSelectDTO.getUnitId())
                    || StringUtils.isBlank(propertyArrearPeopleSelectDTO.getRoomId()) || StringUtils.isBlank(propertyArrearPeopleSelectDTO.getTime())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyArrearPeopleSelectDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            if (!"0.5".equals(propertyArrearPeopleSelectDTO.getTime()) && StringHandlerUtil.strToIntDef(propertyArrearPeopleSelectDTO.getTime(), -1) == -1) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            iPropertyArrearPeopleSelectServiceClient.momentRelieve(propertyArrearPeopleSelectDTO);
            PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
            padFaceSyncDataDTO.setOperateType("0");
            padFaceSyncDataDTO.setRoomId(propertyArrearPeopleSelectDTO.getRoomId());
            padFaceSyncDataDTO.setProjectId(propertyArrearPeopleSelectDTO.getProjectId());
            padFaceSyncDataDTO.setSourceSystem(2);
            iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
            return new MessageVO(propertyArrearPeopleSelectDTO.getRoomId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业-物业增值】临时解除限制失败", e);
        }
    }

    /**
     * <desc>
     *      导出欠费住户信息表单
     * </desc>
     *
     * @param propertyArrearPeopleSelectDTO 欠费住户信息DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/05/22
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("export")
    public Object export(PropertyArrearPeopleSelectDTO propertyArrearPeopleSelectDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyArrearPeopleSelectDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyArrearPeopleSelectDTO.class, request);
            if (propertyArrearPeopleSelectDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyArrearPeopleSelectDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            List<PropertyArrearPeopleSelectVO> propertyArrearPeopleSelectVOList = iPropertyArrearPeopleSelectServiceClient.getExportData(propertyArrearPeopleSelectDTO);
            if (propertyArrearPeopleSelectVOList == null || propertyArrearPeopleSelectVOList.isEmpty()) {
                return new MessageVO(PropertyErrorCodeEnum.EXPORT_DATA_EMPTY_ERR.getErrorCode());
            }
            if (propertyArrearPeopleSelectVOList.size() > 2000) {
                return new MessageVO(PropertyErrorCodeEnum.EXPORT_DATA_TOO_MANY_ERR.getErrorCode());
            }
            String[] title = {"序号","住户名称","地址","手机号","应收金额","滞纳金","应缴金额","缴费单数","最长欠费月数","临时解除限制截止至"};
            short rowHeight = 420;
            //创建excel工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建工作表sheet并设置简单格式
            HSSFSheet sheet = workbook.createSheet();
            sheet.setDefaultColumnWidth(20);
            //创建第一行
            HSSFRow row = sheet.createRow(0);
            row.setHeight(rowHeight);
            HSSFCell cell = null;
            //插入第一行数据的表头
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            //写入数据
            for (int carIndex = 0; carIndex < propertyArrearPeopleSelectVOList.size(); carIndex++) {
                PropertyArrearPeopleSelectVO propertyArrearPeopleSelectVO = propertyArrearPeopleSelectVOList.get(carIndex);
                int rowIndex = carIndex + 1; // 第一行已为标题行
                HSSFRow dataRow = sheet.createRow(rowIndex);
                dataRow.setHeight(rowHeight);
                HSSFCell noteCell = dataRow.createCell(0);
                noteCell.setCellValue(rowIndex);
                noteCell = dataRow.createCell(1);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getRealName());
                noteCell = dataRow.createCell(2);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getAddress());
                noteCell = dataRow.createCell(3);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getPhoneNum());
                noteCell = dataRow.createCell(4);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getDueAmount());
                noteCell = dataRow.createCell(5);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getPenalty());
                noteCell = dataRow.createCell(6);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getPaidAmount());
                noteCell = dataRow.createCell(7);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getFeeCount());
                noteCell = dataRow.createCell(8);
                noteCell.setCellValue(propertyArrearPeopleSelectVO.getMaxArrearageMonth());
                noteCell = dataRow.createCell(9);
                noteCell.setCellValue("1".equals(propertyArrearPeopleSelectVO.getMomentRelieveTime()) ? "正常" : propertyArrearPeopleSelectVO.getMomentRelieveTime());
//                noteCell = dataRow.createCell(10);
//                noteCell.setCellValue((propertyArrearPeopleSelectVO.getRushFeeStatus() != null && propertyArrearPeopleSelectVO.getRushFeeStatus() == 1) ? "已配置" : "未配置");
            }
            String fileName = String.format("%s_arrearagePeopleSelect_%s.xls",
                    propertyArrearPeopleSelectDTO.getProjectId(),
                    DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] content = os.toByteArray();
            InputStream exportFileStream = new ByteArrayInputStream(content);
            String exportFileUrl = this.uploadFile(exportFileStream,fileName);
            if (StringUtils.isBlank(exportFileUrl)){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_EXPORT_FILE_SAVE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) exportFileUrl);
        } catch (Exception e) {
            throw new DataAccessException("【物业-物业增值】导出欠费住户信息表单失败", e);
        }
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author wangzhi
     * @createDate 2019/05/22
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName, fileName.lastIndexOf('.') + 1, fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.EXPORT_EXCEL_ZHANG_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

}
